#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "command_manager.h"
#include "iot_uart.h"
#include "iot_errno.h"

CommandManager *create_command_manager()
{
    CommandManager *manager = (CommandManager *)malloc(sizeof(CommandManager));
    if (manager == NULL)
    {
        return NULL;
    }
    manager->commands = NULL;
    manager->count = 0;
    manager->capacity = 0;
    return manager;
}

void add_command(CommandManager *manager, Command *cmd)
{
    if (manager == NULL || cmd == NULL)
    {
        return;
    }
    if (manager->count >= manager->capacity)
    {
        manager->capacity = manager->capacity == 0 ? 1 : manager->capacity * 2;
        manager->commands = (Command **)realloc(manager->commands, manager->capacity * sizeof(Command *));
    }
    manager->commands[manager->count++] = cmd;
}

void execute_command(CommandManager *manager, int index, char *response, size_t response_size)
{
    if (manager == NULL || response == NULL || index < 0 || index >= manager->count)
    {
        return;
    }
    int32_t ret = manager->commands[index]->execute(manager->commands[index], response, response_size);
    if (ret == IOT_SUCCESS)
    {
        printf("Command %d executed successfully: %s\n", index + 1, response);
    }
    else
    {
        printf("Command %d execution failed\n", index + 1);
    }
}

Command *get_command(CommandManager *manager, int index)
{
    if (manager == NULL || index < 0 || index >= manager->count)
    {
        return NULL;
    }
    return manager->commands[index];
}

void free_command_manager(CommandManager *manager)
{
    if (manager == NULL)
    {
        return;
    }
    for (int i = 0; i < manager->count; i++)
    {
        free_command(manager->commands[i]);
    }
    free(manager->commands);
    free(manager);
}